//
//  FbCell.m
//  FrogDrying
//
//  Created by Le Thanh Hai on 5/19/13.
//
//

#import "FbCell.h"

@implementation FbCell
@synthesize facebookId, avatar;

+(UIImage *)loadFromCacheImageId:(NSString *)imageId
{
    NSString* path = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Library/Caches/%@.png", imageId]];
    BOOL fileExist = [[NSFileManager defaultManager] fileExistsAtPath:path];
    if (fileExist) {
        NSData *imageData = [NSData dataWithContentsOfFile:path];
        return [UIImage imageWithData:imageData];
    }
    return nil;
}


+(void)saveImage:(UIImage *)image toCacheWithId:(NSString *)imageId
{
    NSString* path = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Library/Caches/%@.png", imageId]];
    BOOL ok = [[NSFileManager defaultManager] createFileAtPath:path
                                                      contents:nil attributes:nil];
    if (!ok) {
        NSLog(@"Error creating file %@", path);
    } else {
        NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
        [myFileHandle writeData:UIImagePNGRepresentation(image)];
        [myFileHandle closeFile];
    }
}

-(void)setFacebookId:(NSString*)facebookId_
{
    facebookId = [facebookId_ retain];
    if ([FbCell loadFromCacheImageId:facebookId])
    {
        self.avatar.image = [FbCell loadFromCacheImageId:facebookId];
    }
    else
    {
        NSURL *iconURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://graph.facebook.com/%@/picture?type=square", facebookId]];
        dispatch_queue_t thread = dispatch_queue_create(NULL, NULL);
        dispatch_async(thread, ^{
            NSURLRequest *urlRequest = [NSURLRequest requestWithURL:iconURL
                                                        cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                                    timeoutInterval:10.0f];
            NSData *iconData = [NSURLConnection sendSynchronousRequest:urlRequest
                                                     returningResponse:NULL
                                                                 error:NULL];
            UIImage *iconImage = [UIImage imageWithData:iconData];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.avatar.alpha = 0;
                [UIView animateWithDuration:0.3 animations:^{
                    self.avatar.alpha = 1;
                }];
                self.avatar.image = iconImage;
                [FbCell saveImage:iconImage toCacheWithId:self.facebookId];
            });
        });
#if !OS_OBJECT_USE_OBJC
        dispatch_release(thread);
#endif
    }
}
@end
